package com.airclick.merchant.service.impl;

import com.airclick.merchant.entity.MerDomain;
import com.airclick.merchant.repository.MerRepository;
import com.airclick.merchant.service.MerService;
import com.airclick.merchant.utils.CommonResult;
import com.airclick.merchant.utils.DateUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Transactional(rollbackFor=Exception.class)
@Service
public class MerServiceImpl implements MerService {


    @Resource
    private MerRepository merRepository;

    @Override
    public String findAllByUsername(String username) {
        return merRepository.findAllByUsername(username);
    }

    @Override
    public int updatePassword(String userName, String newpassword) {
        return merRepository.updatePassword(userName,newpassword);
    }

//    @Override
//    public List<MerDomain> merDomainList(String status,String startTime , String endTime,Integer pageNum ,Integer pageSize) {
//
//        Integer start = (pageNum-1)*pageSize;
//
//        return merRepository.merDomainList(status,startTime ,endTime,start,pageSize);
//    }

    @Override
    public MerDomain merDomainUser(String id) {
        return merRepository.findAllById(id);
    }

    @Override
    public int updateUser(String id, String status ,String note) {
        return merRepository.updateUser(id,status,note);
    }

    @Override
    public MerDomain addUser(String userName, String password, String email) {

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(password);
        MerDomain merDomain = new MerDomain();
        merDomain.setUserName(userName);
        merDomain.setPassword(encodePassword);
        merDomain.setEmail(email);
        merDomain.setStatus(1);
        merDomain.setAdminId(merchantMark());
        merDomain.setDeleteState(1);
        merDomain.setIsSuperShop(0);
        return merRepository.save(merDomain);

    }

    public static String merchantMark(){
        String date = DateUtil.getSdfTimess();

        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < 12; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(1);
            switch (type){
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(9));
                    break;
                default:
                    break;
            }
        }

        return date+uid.toString();
    }


    @Override
    public long merConunt() {
        return merRepository.count();
    }

    @Override
    public List<String> selectSaveUser() {
        return merRepository.selectSaveUser(getStartTime(),getnowEndTime());
    }

    @Override
    public List<String> theDailyStatistics(String date) {
        return merRepository.theDailyStatistics(date);
    }

    @Override
    public MerDomain selectId(String userName) {
        return merRepository.findAllByUsernameId(userName);
    }

    @Override
    public String merUserEmail(String userName) {
        return merRepository.findAllByUsernames(userName);
    }

    @Override
    public CommonResult merDomainCommon(String status, String startTime, String endTime, Integer pageNum, Integer pageSize) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //定义时间
            Date start = null;
            Date end = null;
            //把参数时间转换为yyyy-MM-dd HH:mm:ss格式
            if (startTime != null || endTime != null) {
                start = sf.parse(startTime);
                end = sf.parse(endTime);
            }
            //JPA分页
            Pageable pageable= PageRequest.of(pageNum-1,pageSize, Sort.Direction.DESC,"gmtCreate");
            Date finalEnd = end;
            Date finalStart = start;
            Specification<MerDomain> specification=(root, criteriaQuery, criteriaBuilder)->{
            List<Predicate>predicates=new ArrayList<>();
            if (StringUtils.isNotBlank(status)){
                predicates.add(criteriaBuilder.equal(root.get("status"),status));
            }
            if (StringUtils.isNotBlank(startTime)||StringUtils.isNotBlank(endTime)){
                predicates.add(criteriaBuilder.between(root.get("gmtCreate"), finalStart, finalEnd));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page page=merRepository.findAll(specification,pageable);
        List content = page.getContent();
        if (content.size()>0){
            return CommonResult.success(page.getContent(),page.getTotalElements());
        }
        return CommonResult.failed("暂无数据");
        } catch (ParseException e) {
            e.printStackTrace();
            return CommonResult.failed("");
        }
    }

    /**
     * 获取当天时间的开始时间
     * @return
     */
    public static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    /**
     * 获取当天时间结束时间
     * @return
     */
    public static Date getnowEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

}
